/*
 * Created on Aug 2, 2004
 */
package org.vectrics.company.web.struts;

import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.vectrics.SystemException;
import org.vectrics.common.util.DateSync;
import org.vectrics.common.util.StringUtils;
import org.vectrics.company.Company;
import org.vectrics.company.CompanyPerson;
import org.vectrics.company.CompanyPersonGroupType;
import org.vectrics.company.CompanyPersonRole;
import org.vectrics.company.CompanyPersonRoleType;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.struts.tag.CompanyGroupTypeSelectorTag;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.user.Person;


/**
 * @author mmoore
 */
public class SaveCompanyPersonRoleAction extends RequestFormAction {
	private transient final Logger log = Logger.getLogger(SaveCompanyPersonRoleAction.class);
	/* 
	 * @see org.vectrics.company.web.struts.RequestFormAction#createForm()
	 */
	protected ActionForm createForm() {
		return null;
	}

	/* (non-Javadoc)
	 * @see org.vectrics.company.web.struts.RequestFormAction#fillForm(org.apache.struts.action.ActionForm, 
	 * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected String fillForm(ActionForm formIn, Request request,
			HttpServletResponse response) {
		Locale locale = request.getLocale();
		CompanyPersonRoleForm form = (CompanyPersonRoleForm)formIn;
		CompanyPerson companyPerson = null;
		Company company = null;
		Person person = null;
		CompanyPersonRole role = null;
		
		company = CoreServiceLocator.getCompanyService().findCompany(new Long(form.getCompanyId()));
		person = CoreServiceLocator.getPersonService().findPersonById(new Long(form.getPersonId()));
		
		companyPerson = CoreServiceLocator.getCompanyService().findCompanyPerson(company, person);
		
		
		if (companyPerson != null) {
		    if ((form.getCompanyPersonRoleId() != null) && (form.getCompanyPersonRoleId().trim().length() > 0)) {
		        role = companyPerson.findRole(new Long(form.getCompanyPersonRoleId()));
		    }
		} else {
			companyPerson = new CompanyPerson();
			companyPerson.setPerson(person);
			companyPerson.setCompany(company);
			companyPerson.setDateStart(DateSync.getCurrentTime());
		}
		
		if (role == null) {
		    role = new CompanyPersonRole();
		    companyPerson.addRole(role);
		}
		
		try {
		    role.setDateStart(CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(locale).parse(form.getDateStart()));
		} catch (Exception ex) {
		    throw new SystemException("Exception parsing date: " + form.getDateStart());
		}
		
		if ((form.getDateEnd() != null) && (form.getDateEnd().trim().length() > 0)) {
			try {
			    role.setDateEnd(CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(locale).parse(form.getDateEnd()));
			} catch (Exception ex) {
			    throw new SystemException("Exception parsing date: " + form.getDateEnd());
			}
		} 
		CompanyPersonRoleType roleType = CoreServiceLocator.getCompanyService().findCompanyPersonRoleType(form.getRoleType());
		role.setRoleType(roleType);
		role.setTitle(form.getTitle());
		
		setRoleGroups(role, request);
		
		CoreServiceLocator.getCompanyService().updateCompanyPerson(companyPerson);
		ThreadProperties.forcedCommit();
		
		request.setAttribute("companyPersonId", (String)companyPerson.getId().toString());
		log.info("Attribute companyPersonId=" + request.getAttribute("companyPersonId"));

        request.setAttribute("companyPersonForm", form);

        request.setAttribute("personId", person.getId());
        request.setAttribute("userId", person.getId());
		
		return "success";
	}

	
	public void setRoleGroups(CompanyPersonRole role, Request request) {
		List groupTypes = CoreServiceLocator.getCompanyService().findCompanyGroupTypes();
		Iterator iter = groupTypes.iterator();
		while (iter.hasNext()) {
			CompanyPersonGroupType groupType = (CompanyPersonGroupType)iter.next();
			String paramName = CompanyGroupTypeSelectorTag.getParamName(groupType);
			String paramValue = request.getParameter(paramName);
			if (StringUtils.isNullOrBlank(paramValue) == false) {
				log.debug("Group selected: " + groupType.getCode() + "  Adding membership, param=" + paramValue);
				role.addGroupMembership(groupType);
			} else {
				log.debug("Group type not selected: " + groupType.getCode() + "  Removing membership");
				role.removeGroupMembership(groupType);
			}
		}
		
	}
	
	@Override
	protected String doExecute(VectricsActionData actionData) throws JspException {
		
		if (actionData.wasButtonPressed("cancel")) {
			CompanyPersonRoleForm form = (CompanyPersonRoleForm) actionData.getForm();
			Request request=actionData.getRequest();
			CompanyPerson companyPerson = null;
			Company company = null;
			Person person = null;
			
			company = CoreServiceLocator.getCompanyService().findCompany(new Long(form.getCompanyId()));
			person = CoreServiceLocator.getPersonService().findPersonById(new Long(form.getPersonId()));
			
			companyPerson = CoreServiceLocator.getCompanyService().findCompanyPerson(company, person);
			if (companyPerson!=null) {
				request.setAttribute("companyPersonId", (String)companyPerson.getId().toString());
			}
			return "cancel";
		}
		return super.doExecute(actionData);
	}
	
}
